# 读取数据
from pyecharts.charts import Line, Bar, Timeline
from pyecharts.globals import ThemeType
from pyecharts.options import LabelOpts

f=open("F:/Python/res/1960-2019全球GDP数据.csv","r",encoding="GB2312")
data_lines=f.readlines()
# 关闭数据
f.close()
# print(type(data_lines))
# print(data_lines)
# 第一行数据多余了，删除掉
data_lines.pop(0)
# 把数据转为字典
data_dict={}
for line in data_lines:
    year=int(line.split(",")[0])
    conutry=line.split(",")[1]
    gdp=float(line.split(",")[2])
    try:
        data_dict[year].append([conutry,gdp])
    except KeyError:
        data_dict[year]=[]
        data_dict[year].append([conutry,gdp])
# 创建时间线对象
line=Timeline(
    {"theme":ThemeType.LIGHT}
)
# 排序年份
sorted_year_list=sorted(data_dict.keys())
for year in sorted_year_list:
    data_dict[year].sort(key=lambda x:x[1],reverse=True)
    # 取出前八名的国家
    year_data=data_dict[year][0:8]
    x_data=[]
    y_data=[]
    for country_gdp in year_data:
        x_data.append(country_gdp[0])
        y_data.append(country_gdp[1]/100000000)
    # 创建柱状图
    x_data.reverse()
    y_data.reverse()
    bar=Bar()
    bar.add_xaxis(x_data)
    bar.add_yaxis("GDP（亿）",y_data,label_opts=LabelOpts(position="right"))
    bar.reversal_axis()

    # 数据添加到时间线内
    line.add(bar,str(year))
# 设置时间线自动播放
line.add_schema(
    play_interval=1000,
    is_timeline_show=True,
    is_auto_play=True,
    is_loop_play=True
)
# 绘图
line.render("1960-2019年世界前八GDP国家.html")